<template>
  <div class="punch-container">
    <!-- 当前时间显示 - 放大版 -->
    <div class="time-display">
      <div class="time-text">{{ currentTime }}</div>
      <div class="date-text">{{ currentDate }}</div>
    </div>

    <!-- 打卡按钮 -->
    <div class="punch-button">
      <el-button type="primary" size="large" @click="handlePunch" class="punch-btn">
        打卡
      </el-button>
    </div>
  </div>
</template>
  
<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { ElMessage } from 'element-plus'
import { checkInOrOut } from '../../api/attendance.js'

// 当前时间
const currentTime = ref('')
const currentDate = ref('')
let timeInterval = null

// 打卡状态
const isPunching = ref(false)
const lastPunchResult = ref(null)

// 更新时间
const updateTime = () => {
  const now = new Date()
  currentTime.value = now.toLocaleTimeString('zh-CN', { hour12: false })
  currentDate.value = now.toLocaleDateString('zh-CN', { 
    year: 'numeric', 
    month: 'long', 
    day: 'numeric',
    weekday: 'long'
  })
}

// 打卡处理
const handlePunch = () => {
  if (isPunching.value) return
  
  isPunching.value = true
  
  checkInOrOut().then(res => {
    // 根据ResultVO结构处理响应
    if (res.flag) {
      ElMessage.success(res.reason || '打卡成功')
      lastPunchResult.value = res.result
    } else {
      ElMessage.warning(res.reason || '打卡未完成')
    }
  }).catch(err => {
    console.error('打卡失败:', err)
    
    // 错误处理
    let errorMessage = '打卡失败，请稍后重试'
    
    if (err.response) {
      // 处理后端返回的错误信息
      if (err.response.data && err.response.data.reason) {
        errorMessage = err.response.data.reason
      } else {
        errorMessage = `服务器错误: ${err.response.status}`
      }
    } else if (err.request) {
      errorMessage = '网络错误，请检查网络连接'
    }
    
    ElMessage.error(errorMessage)
    
    // 未认证处理
    if (err.response?.status === 401) {
      router.push('/login')
    }
  }).finally(() => {
    isPunching.value = false
  })
}

// 生命周期钩子
onMounted(() => {
  updateTime()
  timeInterval = setInterval(updateTime, 1000)
})

onBeforeUnmount(() => {
  clearInterval(timeInterval)
})
</script>
  
  <style scoped>
.punch-container {
    height: 85vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 30px;
}

.time-display {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;
}

.time-text {
  font-size: 30px;
  font-weight: bold;
  color: #333;
  font-family: "Arial", sans-serif;
}

.date-text {
  font-size: 20px;
  color: #666;
}

.punch-button {
  margin-top: 30px;
}

.punch-btn {
  width: 150px;
  height: 150px;
  font-size: 28px;
  border-radius: 50%;
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
  transition: all 0.3s;
}

.punch-btn:hover {
  transform: scale(1.05);
  box-shadow: 0 6px 16px rgba(64, 158, 255, 0.4);
}
</style>